/*
 * main.c
 *
 *  Created on: 11.09.2012
 *      Author: Nils
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <avr/pgmspace.h>
#include "USI_TWI_Master.h"

/* KONSTANTEN */

#define I2C_ADDRESS_MASTER 0x00
#define I2C_ADDRESS_PROGRAMING 0x01
#define I2C_ADDRESS_SYNC 0x02
#define I2C_ADDRESS_START 0x03
#define I2C_ADDRESS_NOTHING 0x00

/* MACROS */

#define ADDRESS_WITHOUT_READBIT(__address__) ((__address__) & ~1)
#define ADDRESS(__address__) ADDRESS_WITHOUT_READBIT((__address__) << 1)

#define ENABLE_INTERRUPT sei
#define DISABLE_INTERRUPT cli

/* TYPES */

typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned long uint32;
typedef long int32;

/* VARIABLEN */

/*const uint8 colors[5][4] PROGMEM = {
		{ 255, 0, 0, 0 },
		{ 255, 0, 0, 0 },
		{ 255, 0, 0, 0 },
		{ 255, 0, 0, 0 },
		{ 255, 0, 0, 0 }
};*/

uint8 hiModule=0;

/* INIT-FUNCTIONEN */

void IO_init(){
	DDRA = 0b000;
	DDRB = 0b00000000;
	DDRD = 0b0000000;

	PORTA = 0b000;
	PORTB = 0b00000000;
	PORTD = 0b0000000;
}

void i2c_init(){
	hiModule=0;
	USI_TWI_Master_Initialise();
}

/* FUNCTIONEN */

void i2c_setModuleColor(uint8 address, uint8 red, uint8 green, uint8 blue, uint8 white, uint8 progNext){
	uint8 data[6] = { ADDRESS(address + I2C_ADDRESS_START), red, green, blue, white, progNext };
	if(USI_TWI_Start_Transceiver_With_Data((uint8*)data, 6)==FALSE){
		if(USI_TWI_Get_State_Info()==USI_TWI_NO_ACK_ON_ADDRESS)
			hiModule = address;
	}
}

void i2c_sync(){
	uint8 data[1] = {ADDRESS(I2C_ADDRESS_SYNC)};
	USI_TWI_Start_Transceiver_With_Data((uint8*)data, 1);
}

void i2c_lookForNewModule(){
	uint8 data[2] = {ADDRESS(I2C_ADDRESS_PROGRAMING), hiModule+I2C_ADDRESS_START};
	if(USI_TWI_Start_Transceiver_With_Data((uint8*)data, 2)==TRUE)
		hiModule++;
}

/* MAIN */

int main(){
	IO_init();
	i2c_init();

	uint8 r=255;
	uint8 g=0;
	uint8 b=0;
	uint8 up=0;
	while(1){
		switch(up){
		case 0:
			g++;
			if(g==255)
				up=1;
			break;
		case 1:
			r--;
			if(r==0)
				up=2;
			break;
		case 2:
			b++;
			if(b==255)
				up=3;
			break;
		case 3:
			g--;
			if(g==0)
				up=4;
			break;
		case 4:
			r++;
			if(r==255)
				up=5;
			break;
		case 5:
			b--;
			if(b==0)
				up=0;
			break;
		}
		i2c_setModuleColor(0, r, g, b, 0, 0);
		i2c_sync();
		_delay_ms(10);
		/*if(hiModule==0)
			i2c_lookForNewModule();
		else{
			for(uint8_t i=0; i<253; i++){
				if(i>=hiModule)
					//i2c_lookForNewModule();
					break;
				if(i==hiModule-1){
					i2c_setModuleColor(i, colors[i][0], colors[i][1], colors[i][2], colors[i][3], 1);
				}else
					i2c_setModuleColor(i, colors[i][0], colors[i][1], colors[i][2], colors[i][3], 0);
			}
			i2c_sync();
		}*/
	}
}

